package com.mingweicai.intergration.thread;

import java.util.concurrent.Semaphore;

class ZeroEvenOdd {

  private volatile int count = 0;
  private Semaphore sZero = new Semaphore(1);
  private Semaphore sEven = new Semaphore(0);
  private Semaphore sOdd = new Semaphore(0);

  private int n;

  public ZeroEvenOdd(int n) {
    this.n = n;
  }

  // 构造函数
  public void zero() { // 仅打印出 0
    try {
      for(int i=1; i<=n; i++){
        sZero.acquire();
        System.out.print("0");
        count++;
        if((count & 1) == 0){
          sEven.release();
        }else{
          sOdd.release();
        }
      }
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

  public void even() { // 仅打印出 偶数
    for(int i=2 ; i<=n; i+=2){
      try {
        sEven.acquire();
        System.out.print(i);
        sZero.release();
      }catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  public void odd() { // 仅打印出 奇数
    for(int i=1; i<=n; i+=2){
      try {
        sOdd.acquire();
        System.out.print(i);
        sZero.release();
      }catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}
